import axios from 'axios'
import { ElMessage, ElLoading } from 'element-plus'
import { useUserStore } from '@/stores/user'
import { getMAC } from '@/utils/getMAC';
const instance = axios.create({
  baseURL: import.meta.env.VITE_APP_API,
  withCredentials: false,
})



// 请求拦截器
instance.interceptors.request.use(
  async config => {
    const macAddress = await getMAC();
    config = {
      neddLogin: true,
      ...config,
    }

    const userStore = useUserStore()
    // console.log(userStore.apiurls.VITE_APP_API);
    // console.log(instance.defaults);
    
    
    // instance.defaults.baseURL = userStore.apiurls.VITE_APP_API || import.meta.env.VITE_APP_API
    if (config.neddLogin) {
      if (userStore.checkLogin()) {

        config.headers['Authorization'] = `TOKEN ` + userStore.token
      }
    }
    config.headers['PLANTCODE'] = `${userStore.packageJs.plantcode}=${userStore.packageJs.plantcode2}`
    config.headers['MAC'] = macAddress

    return config
  },
  error => {
    const userStore = useUserStore()
    ElMessage.error(userStore.language.data.message.apiTimeout)
    Promise.reject(error)
  }
)

// 相应拦截器
instance.interceptors.response.use(
  response => {
    const { data, status } = response
    const userStore = useUserStore()
    
    let langMsg = localStorage.getItem(`sp_language`) == 'zh' ? data.msg_lang.text_zh : data.msg_lang.text_en
    if (status && status == 200) {
      if ([401].includes(data.code)) {
        ElMessage.warning(langMsg || data.data.msg || userStore.language.data.message.accountExpiratio)
        const userStore = useUserStore()
        userStore.logout()
        // return Promise.reject(data)
      } else if (data.code != 200) {
        ElMessage.error(langMsg || data.msg)
        return Promise.reject(data)
      }

      return data
    } else {

      ElMessage.error(userStore.language.data.message.apiError)
      return Promise.reject(data)
    }
  },
  error => {
    const userStore = useUserStore()
    let langMsg = localStorage.getItem(`sp_language`) == 'zh' ? error?.response?.data?.msg_lang?.text_zh : error?.response?.data?.msg_lang?.text_en
    if (error?.response?.status == 401 || error?.response?.status == 400) {
      ElMessage.warning(langMsg || error?.response?.data?.msg || userStore.language.data.message.accountExpiratio)
      const userStore = useUserStore()
      userStore.logout()
      return
    } else if (error?.response?.status == undefined) {
      // ElMessage.error('请求超时')
      const userStore = useUserStore()
      userStore.openerrordialog()
    } else {
      ElMessage.error(userStore.language.data.message.apiTimeout)
      // const userStore = useUserStore()
      // userStore.openerrordialog()
    }


    return Promise.reject(error)
  }
)

export const http = instance
export default instance
